package mytomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class MyTomcat {

	private int port = 8080;
	private Map<String, String> urlServletMap = new HashMap<>();
	
	public MyTomcat(int port) {
		this.port = port;
	}
	
	public void start(){
		initServletMapping();
		
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port);
			System.out.println("My tomcat is start..");
			
			while(true){
				Socket socket = serverSocket.accept();
				System.out.println("receive request...");
				new Thread(new Runnable() {
					public void run() {
						try {
						InputStream inputStream = socket.getInputStream();
						OutputStream outputStream = socket.getOutputStream();
						
						MyRequest request = new MyRequest(inputStream);
						MyResponse response = new MyResponse(outputStream);
						
						dispatch(request, response);
						socket.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}).start();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(serverSocket!=null && !serverSocket.isClosed()){
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	private void initServletMapping() {
		for(ServletMapping servletMapping: ServletMappingConfig.servletMappings){
			urlServletMap.put(servletMapping.getUrl(), servletMapping.getClazz());
		}
	}
	
	@SuppressWarnings("unchecked")
	private void dispatch(MyRequest request, MyResponse response) {
		System.out.println("dispatch: "+request.getUrl());
		String clazz = urlServletMap.get(request.getUrl());
		if(clazz==null){
			return;
		}
		try {
			Class<MySerlvet> myServletClass = (Class<MySerlvet>) Class.forName(clazz);
			MySerlvet serlvetInstance = myServletClass.newInstance();
			serlvetInstance.service(request, response);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		MyTomcat tomcat = new MyTomcat(8888);
		tomcat.start();
	}
	
}
